package com.yuyou.fn.common.rocketmq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.MessageListener;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

public class Consumer {

    private String namesrvAddr ;

    public String getNamesrvAddr() {
        return namesrvAddr;
    }

    public void setNamesrvAddr(String namesrvAddr) {
        this.namesrvAddr = namesrvAddr;
    }

    public void subscribe(String topic, String groupName, MessageListener messageListener ){
        this.subscribe(topic,null , groupName,messageListener);
    }

    public void subscribe(String topic,String tags, String groupName, MessageListener messageListener ){
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(topic +"_"+groupName );
        consumer.setNamesrvAddr(namesrvAddr);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        try {
            consumer.subscribe(topic, tags == null ? "*" : tags);
        } catch (MQClientException e) {
            throw new RuntimeException("Subscribe fail : topic=" + topic+",groupName="+groupName ,e );
        }
        consumer.registerMessageListener(messageListener);
        try {
            consumer.start();
        } catch (MQClientException e) {
            throw new RuntimeException("Start fail : topic=" + topic+",groupName="+groupName ,e );
        }
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                consumer.shutdown();
            }
        });
    }

    public void subscribeBroadcast(String topic ,String tags, MessageListenerConcurrently messageListener ){
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(topic +"_Broadcast" );
        consumer.setNamesrvAddr(namesrvAddr);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        consumer.setMessageModel(MessageModel.BROADCASTING);
        try {
            consumer.subscribe(topic, tags == null ? "*" : tags);
        } catch (MQClientException e) {
            throw new RuntimeException("Subscribe fail : topic=" + topic  ,e );
        }
        consumer.registerMessageListener(messageListener);
        try {
            consumer.start();
        } catch (MQClientException e) {
            throw new RuntimeException("Start fail : topic=" + topic ,e );
        }
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                consumer.shutdown();
            }
        });
    }

}
